package com.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import com.bean.Chat;
import com.bean.User;
import com.dao.ChatMapper;
import com.dao.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.rong.ApiHttpClient;
import io.rong.models.CustomMessage;
import io.rong.models.FormatType;
import io.rong.models.SdkHttpResult;

/**
 * Servlet implementation class WeixinServlet
 */
public class WeixinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//返回值
	int jsonFlag =0;
	//第三方登录key,secret
	String key = null;
	String secret = null;
	//对server sdk返回的封装
	SdkHttpResult result = null;
	 private static SqlSessionFactory sqlSessionFactory;
	 private static Reader reader; 
	 private static SqlSession sqlSession;
	 UserMapper objUserMapper;
	 ChatMapper objChatMapper;
	 Transaction  objTransaction;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WeixinServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/** */
	public void init() throws ServletException {
		// custom initialization code
                  
		try {
			reader = Resources.getResourceAsReader("com/Configuration.xml");
			
		    sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		        
		    sqlSession = sqlSessionFactory.openSession();
		    
		    TransactionFactory transactionFactory = new JdbcTransactionFactory();
		    
		    objTransaction = transactionFactory.newTransaction(sqlSession.getConnection());
		      
		    objUserMapper = sqlSession.getMapper(UserMapper.class);
		        
		    objChatMapper = sqlSession.getMapper(ChatMapper.class);
		    
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
   
	}

	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String uri = request.getRequestURI();
		String patternAction = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
		PrintWriter out = response.getWriter();

		/**
		 * 登录第三方聊天,获取token(必须登录)
		 */
		if ("/ChatGotTokenAction".equals(patternAction)) {
			key = request.getParameter("sdkInit");
			secret = request.getParameter("sdkSecret");
			String strUserId = request.getParameter("userId");
			String strName = request.getParameter("name");
			String strPortraitUri = request.getParameter("portraitUri");

			try {
				result = ApiHttpClient.getToken(key, secret, strUserId, strName, strPortraitUri, FormatType.json);
				out.print(result);
				// gettoken={"code":"200","result":{"code":200,"userId":"66976","token":"2EU19Dw89m9WJ6dDsUAa/4BAISxMYFYowj+M2fzXRlE15+doKDPwfoihkiNIccp2P9Hb5fmWkM0S6vUwB0B+9w=="}}
				// System.out.println("gettoken=" + result);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		/**
		 * 用户注册
		 */
		else if("/ChatUserRegisterAction".equals(patternAction)){
			User objUser = new User();
			//邮箱
			String strMail = request.getParameter("email");
			objUser.setUserMail(strMail);
			//密码
			String strPwd = request.getParameter("password");
			objUser.setUserPwd(strPwd);
			//手机
			String strPhone = request.getParameter("mobile");
			objUser.setUserPhone(strPhone);
			//昵称
			String strNickname = request.getParameter("username");
			objUser.setUserNickname(strNickname);
			int intUserId = 0;
			objUser.setUserId(intUserId);
		try {
			
			jsonFlag = objUserMapper.insert(objUser);
			
		} catch (Exception e) {
			// TODO: handle exception
			try {
				e.printStackTrace();
				objTransaction.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}finally {
			try {
				objTransaction.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(jsonFlag>0){
				//注册参数
				String strParam = "email="+objUser.getUserMail()+"&mobile="+objUser.getUserPhone()+"&username="+objUser.getUserNickname()+"&password="+objUser.getUserPwd();
				//发送post请求
				out.print(sendPost("http://webim.demo.rong.io/reg",strParam));
			}
		}
		
		/**
		 * 用户留言审核初始化页面
		 */
		else if("/UserChatReviewIndex".equals(patternAction)){
			 request.getRequestDispatcher("layout/userChatReviewIndex.jsp").forward(request,response);
		}
		
		/**
		 * 检索用户留言初始化页面
		 */
		else if("/UserChatSearchIndex".equals(patternAction)){
			response.sendRedirect("layout/userChatReviewOper.jsp");
		}
		
		/**
		 * 检索用户留言
		 */
		else if("/UserChatSearchAction".equals(patternAction)){
			
			int intPageNum = Integer.valueOf(request.getParameter("page")==null?"1":request.getParameter("page"));
			
			int intPageSize = Integer.valueOf(request.getParameter("rows")==null?"10":request.getParameter("rows"));
			
			//留言状态1：未通过
			int strStatus = 1;
			//分页查询用户留言
			PageHelper.startPage(intPageNum,intPageSize);
			PageHelper.orderBy("chat_id");
			List<Chat> listChat = objChatMapper.selectListChatInfo(strStatus);
			PageInfo<Chat> pageInfo = new PageInfo<Chat>(listChat);
			request.setAttribute("listChat", pageInfo.getList());
			request.setAttribute("intCount", pageInfo.getTotal());
			request.getRequestDispatcher("layout/userChatReviewOper.jsp").forward(request,response);
		}
	
		
		/**
		 * 审核用户留言
		 */
		else if("/UserChatReviewAction".equals(patternAction)){
			Chat objChat = new Chat();
			//审核表主键id
			int strId = Integer.valueOf(request.getParameter("id"));
			objChat.setChatId(strId);
			//审核状态0：通过1：不通过
			int strStatus = Integer.valueOf(request.getParameter("status"));
			objChat.setChatStatus(strStatus);
			try {
				jsonFlag = objChatMapper.updateByPrimaryKeySelective(objChat);
			} catch (Exception e2) {
				// TODO: handle exception
				try {
					objTransaction.rollback();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}finally {
				try {
					objTransaction.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			//成功就发送消息给第三方服务器
			if(jsonFlag>0&&strStatus==0){
				//获取用户对象
				objChat = objChatMapper.selectByPrimaryKey(strId);
				//用户id
				String fromUserId =String.valueOf(objChat.getChatUserId());
				//聊天室id
				List<String> toChatroomIds = new ArrayList<String>();
				//自定义message类,发送的消息
				CustomMessage objMessage = new CustomMessage();
				objMessage.setContent(objChat.getChatContent());
				//发送聊天室信息
				try {
					result = ApiHttpClient.publishChatroomMessage(key, secret, fromUserId, toChatroomIds, objMessage, FormatType.json);
					System.out.println("审核通过用户留言发送这条消息:"+result);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 后台发出请求第三方注册用户
	 * @param url 
	 * @param objUser
	 */
	private String sendPost(String strUrl, String strParam) {
		// TODO Auto-generated method stub
		 PrintWriter out = null;
	     BufferedReader in = null;
	     String result = "";
	     try {
				URL realUrl = new URL(strUrl);
	            // 打开和URL之间的连接
	            URLConnection conn = realUrl.openConnection();
	            // 设置通用的请求属性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 发送POST请求必须设置如下两行
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            // 获取URLConnection对象对应的输出流
	            out = new PrintWriter(conn.getOutputStream());
	            // 发送请求参数
	            out.print(strParam);
	            // flush输出流的缓冲
	            out.flush();
	            // 定义BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
		}
	     //使用finally块来关闭输出流、输入流
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	                ex.printStackTrace();
	            }
	        }
	     return result;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
